package com.springbootmybatis.config;


import com.springbootmybatis.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FilterConfig implements Filter {

    @Autowired
    SessionUtil sessionUtil;

    @Override
    public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String servletPath = request.getServletPath();
       if (servletPath.equals("/") || servletPath.equals("/static/**") || servletPath.equals("/user/login")
               || servletPath.equals("/user/get-verify-code")) {
           filterChain.doFilter(request, response);
       } else {
           String sessionId = request.getSession().getId();
           Object session = sessionUtil.getAttribute(sessionId);
           if (session == null) {
               response.sendRedirect("/");
           } else {
               System.out.println(session);
               filterChain.doFilter(request, response);
           }
       }
    }
}
